// mine/pages/car-details/car-details.js
import http from '../../../utils/https.js'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    vehicleId: '',
    vehicleInfo: {},
    parkingSpaces: [],
    loading: true,
    parkingLoading: true, // 车位加载状态
    hasParkingSpace: true, // 车位信息是否存在
    rawParkingData: [], // 存储原始车位数据
    
    // 月卡相关数据
    monthlyCardInfo: null, // 月卡信息
    hasMonthlyCard: false, // 是否有月卡
    monthlyCardLoading: true, // 月卡加载状态
    
    // 车辆类型
    vehicleType: '', // 车辆类型：'monthly' 或 'private'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('车辆详情页面加载，参数:', options);
    
    if (options.id) {
      this.setData({
        vehicleId: options.id
      });
      this.getVehicleDetails(options.id);
      

    } else {
      wx.showToast({
        title: '车辆ID参数缺失',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 获取车辆详细信息
  getVehicleDetails(vehicleId) {
    console.log('获取车辆详细信息，ID:', vehicleId);
    
    http.get('vehicle/vehicle/list', { residentId: wx.getStorageSync('residentId') })
      .then(res => {
        if (res.code === 200 && res.rows) {
          const vehicle = res.rows.find(v => v.id == vehicleId);
          if (vehicle) {
            // 处理图片URL
            if (vehicle.imageUrl && !vehicle.imageUrl.startsWith('http')) {
              vehicle.imageUrl = 'http://localhost:8080' + vehicle.imageUrl;
            }
            
            console.log('获取到车辆信息:', vehicle);
            console.log('车辆sort字段:', vehicle.sort);
            
            // 根据sort字段判断车辆类型
            let vehicleType = '';
            if (vehicle.sort === 0) {
              vehicleType = 'temporary'; // 临时停车
              console.log('该车辆是临时停车，显示购买月卡按钮');
            } else if (vehicle.sort === 1) {
              vehicleType = 'monthly'; // 月卡车辆
              console.log('该车辆是月卡车辆，开始查询月卡信息');
            } else if (vehicle.sort === 2) {
              vehicleType = 'private'; // 私家车
              console.log('该车辆是私家车，开始查询车位信息');
            } else {
              console.log('车辆sort字段值异常:', vehicle.sort);
            }
            
            this.setData({
              vehicleInfo: vehicle,
              vehicleType: vehicleType,
              loading: false
            });
            
            // 根据车辆类型调用相应的接口
            if (vehicleType === 'temporary') {
              // 临时停车车辆不调用任何接口，只显示购买月卡按钮
              console.log('临时停车车辆，不调用查询接口');
            } else if (vehicleType === 'monthly') {
              this.getMonthlyCardInfo(vehicleId);
            } else if (vehicleType === 'private') {
              this.getParkingDetails(vehicleId);
            }
            
            console.log('车辆信息获取成功:', vehicle);
          } else {
            wx.showToast({
              title: '未找到车辆信息',
              icon: 'none'
            });
          }
        }
      })
      .catch(err => {
        console.error('获取车辆信息失败:', err);
        this.setData({ loading: false });
        wx.showToast({
          title: '获取车辆信息失败',
          icon: 'none'
        });
      });
  },

  // 获取车位信息
  getParkingDetails(vehicleId) {
    console.log('获取车位信息，车辆ID:', vehicleId);
    
    // 设置车位信息加载状态
    this.setData({
      parkingLoading: true
    });
    
    // 确保vehicleId是数字类型
    const queryVehicleId = parseInt(vehicleId);
    if (isNaN(queryVehicleId)) {
      console.error('车辆ID无效:', vehicleId);
      this.setData({
        parkingLoading: false,
        parkingSpaces: [],
        hasParkingSpace: false
      });
      return;
    }
    
    console.log('查询车位信息，参数:', { vehicleId: queryVehicleId });
    
    // 尝试不同的参数格式，确保后端能正确识别
    const queryParams = {
      vehicleId: queryVehicleId,
      vehicle_id: queryVehicleId,  // 下划线格式
      id: queryVehicleId           // 备用参数名
    };
    
    console.log('发送查询参数:', queryParams);
    
    // 调用车位信息接口，确保使用正确的参数名
    http.get('parkingSpace/parkingSpace/list', queryParams)
      .then(res => {
        console.log('车位信息接口返回:', res);
        
        if (res.code === 200 && res.rows && res.rows.length > 0) {
          // 保存原始数据用于调试
          this.setData({
            rawParkingData: res.rows, // 保存原始数据
            parkingLoading: false,
            hasParkingSpace: true
          });
          console.log('原始车位数据:', res.rows);
          
          // 分析第一个车位的完整数据结构
          if (res.rows.length > 0) {
            const firstParking = res.rows[0];
            console.log('=== 第一个车位数据结构分析 ===');
            console.log('第一个车位完整数据:', JSON.stringify(firstParking, null, 2));
            
            // 检查关键字段
            if (firstParking.regionManagement) {
              const regionInfo = firstParking.regionManagement;
              console.log('regionManagement存在:', regionInfo);
              console.log('regionManagement.regionName:', regionInfo.regionName);
              console.log('regionManagement.remark:', regionInfo.remark);
            } else {
              console.log('regionManagement不存在');
            }
            
            if (firstParking.regionLocation) {
              const locationInfo = firstParking.regionLocation;
              console.log('regionLocation存在:', locationInfo);
              console.log('regionLocation.locationName:', locationInfo.locationName);
            } else {
              console.log('regionLocation不存在');
            }
            
            if (firstParking.vehicleManagement) {
              const vehicleInfo = firstParking.vehicleManagement;
              console.log('vehicleManagement存在:', vehicleInfo);
              console.log('vehicleManagement.plateNumber:', vehicleInfo.plateNumber);
            } else {
              console.log('vehicleManagement不存在');
            }
            
            console.log('=== 数据结构分析结束 ===');
          }
          
          // 再次过滤，确保只显示属于当前车辆的车位
          const filteredParkingSpaces = res.rows.filter(parking => {
            // 检查车位是否属于当前车辆
            const parkingVehicleId = parking.vehicle_id || parking.vehicleId || parking.vehicle_id;
            const isCurrentVehicle = parkingVehicleId == queryVehicleId;
            
            console.log('车位ID:', parking.id, '车位车辆ID:', parkingVehicleId, '当前车辆ID:', queryVehicleId, '是否匹配:', isCurrentVehicle);
            
            return isCurrentVehicle;
          });
          
          console.log('过滤后的车位信息:', filteredParkingSpaces);
          
          if (filteredParkingSpaces.length > 0) {
            // 处理车位信息，按照指定结构绑定字段
            const processedParkingSpaces = filteredParkingSpaces.map(parking => {
              console.log('=== 处理车位数据开始 ===');
              console.log('完整车位数据:', parking);
              
              // 按照JSON数据结构绑定字段
              let locationName = '未知位置';
              let regionName = '未知区域';
              let remark = '无备注';
              
              // 位置：regionLocation.locationName (根据JSON数据结构)
              if (parking.regionLocation?.locationName) {
                locationName = parking.regionLocation.locationName;
                console.log('成功获取位置信息 - regionLocation.locationName:', locationName);
              } else if (parking.regionManagement?.regionLocation?.locationName) {
                locationName = parking.regionManagement.regionLocation.locationName;
                console.log('成功获取位置信息 - regionManagement.regionLocation.locationName:', locationName);
              } else {
                console.log('位置信息获取失败，使用默认值');
              }
              
              // 区域：regionManagement.regionName
              if (parking.regionManagement?.regionName) {
                regionName = parking.regionManagement.regionName;
                console.log('成功获取区域名称:', regionName);
              }
              
              // 备注：regionManagement.remark
              if (parking.regionManagement?.remark) {
                remark = parking.regionManagement.remark;
                console.log('成功获取备注信息:', remark);
              }
              
              const parkingInfo = {
                id: parking.id,
                // 区域：regionManagement.regionName
                regionName: regionName,
                // 位置：regionLocation.locationName
                locationName: locationName,
                // 备注：regionManagement.remark
                remark: remark
              };
              
              console.log('最终提取的车位信息:', parkingInfo);
              console.log('=== 处理车位数据结束 ===');
              
              return parkingInfo;
            });
            
            this.setData({
              parkingSpaces: processedParkingSpaces,
              parkingLoading: false,
              hasParkingSpace: true
            });
            console.log('车位信息处理完成，共', processedParkingSpaces.length, '个车位');
          } else {
            // 过滤后没有车位信息
            this.setData({
              parkingSpaces: [],
              parkingLoading: false,
              hasParkingSpace: false
            });
            console.log('该车辆暂无车位信息（过滤后）');
          }
        } else {
          // 没有车位信息
          this.setData({
            parkingSpaces: [],
            parkingLoading: false,
            hasParkingSpace: false
          });
          console.log('该车辆暂无车位信息');
        }
      })
      .catch(err => {
        console.error('获取车位信息失败:', err);
        this.setData({
          parkingSpaces: [],
          parkingLoading: false,
          hasParkingSpace: false
        });
        
        wx.showToast({
          title: '车位信息获取失败',
          icon: 'none'
        });
      });
  },

  // 获取月卡信息
  getMonthlyCardInfo(vehicleId) {
    console.log('=== 开始获取月卡信息 ===');
    console.log('车辆ID:', vehicleId);
    console.log('车辆ID类型:', typeof vehicleId);
    
    this.setData({ monthlyCardLoading: true });
    
    // 尝试多种参数名称，因为数据库字段可能是vehicle_id
    const queryParams = {
      vehicleId: vehicleId,
      vehicle_id: vehicleId,
      veh: vehicleId
    };
    
    console.log('查询参数:', queryParams);
    console.log('调用接口: http://localhost:8080/monthlyCard/monthlyCard/list');
    
    // 调用月卡查询接口
    http.get('monthlyCard/monthlyCard/list', queryParams)
      .then(res => {
        console.log('=== 月卡信息接口返回 ===');
        console.log('完整响应:', res);
        console.log('响应状态码:', res.code);
        console.log('响应数据:', res.data);
        console.log('响应数据类型:', typeof res.data);
        console.log('响应rows字段:', res.rows);
        
        // 检查多种可能的数据结构
        let monthlyCardData = null;
        
        if (res.code === 200) {
          // 尝试不同的数据结构
          if (res.data && res.data.length > 0) {
            monthlyCardData = res.data;
            console.log('从res.data获取到月卡数据');
          } else if (res.rows && res.rows.length > 0) {
            monthlyCardData = res.rows;
            console.log('从res.rows获取到月卡数据');
          } else if (res.data && !Array.isArray(res.data)) {
            monthlyCardData = [res.data];
            console.log('从res.data(非数组)获取到月卡数据');
          }
          
          if (monthlyCardData && monthlyCardData.length > 0) {
            // 过滤出属于当前车辆的月卡
            const vehicleMonthlyCards = monthlyCardData.filter(card => {
              const cardVehicleId = card.vehicle_id || card.vehicleId || card.veh;
              const isMatch = cardVehicleId == vehicleId;
              console.log('月卡ID:', card.id, '月卡车辆ID:', cardVehicleId, '当前车辆ID:', vehicleId, '是否匹配:', isMatch);
              return isMatch;
            });
            
            console.log('过滤后的月卡数据:', vehicleMonthlyCards);
            
            if (vehicleMonthlyCards.length > 0) {
              // 查询到月卡信息
              const monthlyCard = vehicleMonthlyCards[0]; // 取第一个月卡
              console.log('获取到月卡信息:', monthlyCard);
              console.log('月卡信息详情:', JSON.stringify(monthlyCard, null, 2));
              
              this.setData({
                monthlyCardInfo: monthlyCard,
                hasMonthlyCard: true,
                monthlyCardLoading: false
              });
              
              console.log('月卡信息设置完成，当前状态:', {
                hasMonthlyCard: this.data.hasMonthlyCard,
                monthlyCardInfo: this.data.monthlyCardInfo
              });
            } else {
              console.log('未找到属于该车辆的月卡信息');
              this.setData({
                monthlyCardInfo: null,
                hasMonthlyCard: false,
                monthlyCardLoading: false
              });
            }
          } else {
            console.log('接口返回数据为空');
            this.setData({
              monthlyCardInfo: null,
              hasMonthlyCard: false,
              monthlyCardLoading: false
            });
          }
        } else {
          console.log('接口返回状态码不是200');
          this.setData({
            monthlyCardInfo: null,
            hasMonthlyCard: false,
            monthlyCardLoading: false
          });
        }
      })
      .catch(err => {
        console.error('获取月卡信息失败:', err);
        console.error('错误详情:', err.message);
        console.error('错误堆栈:', err.stack);
        
        // 尝试备用查询方法
        console.log('尝试备用查询方法...');
        this.tryAlternativeMonthlyCardQuery(vehicleId);
      });
  },

  // 备用月卡查询方法
  tryAlternativeMonthlyCardQuery(vehicleId) {
    console.log('=== 尝试备用月卡查询方法 ===');
    
    // 尝试不同的接口路径
    const alternativeUrls = [
      `monthlyCard/monthlyCard/vehicle/${vehicleId}`,
      `monthlyCard/monthlyCard/${vehicleId}`,
      `monthlyCard/monthlyCard/list?vehicle_id=${vehicleId}`,
      `monthlyCard/monthlyCard/list?veh=${vehicleId}`
    ];
    
    let currentIndex = 0;
    
    const tryNextUrl = () => {
      if (currentIndex >= alternativeUrls.length) {
        console.log('所有备用方法都失败，认为没有月卡');
        this.setData({
          monthlyCardInfo: null,
          hasMonthlyCard: false,
          monthlyCardLoading: false
        });
        return;
      }
      
      const url = alternativeUrls[currentIndex];
      console.log(`尝试备用接口 ${currentIndex + 1}: ${url}`);
      
      http.get(url)
        .then(res => {
          console.log(`备用接口 ${currentIndex + 1} 返回:`, res);
          
          if (res.code === 200 && res.data) {
            // 查询到月卡信息
            console.log('备用方法获取到月卡信息:', res.data);
            this.setData({
              monthlyCardInfo: res.data,
              hasMonthlyCard: true,
              monthlyCardLoading: false
            });
          } else {
            // 尝试下一个接口
            currentIndex++;
            tryNextUrl();
          }
        })
        .catch(err => {
          console.error(`备用接口 ${currentIndex + 1} 失败:`, err);
          // 尝试下一个接口
          currentIndex++;
          tryNextUrl();
        });
    };
    
    tryNextUrl();
  },

  // 跳转到购买月卡或月卡详情页面
  gotoMonthlyCard: function() {
    console.log('=== 开始跳转月卡页面 ===');
    console.log('hasMonthlyCard:', this.data.hasMonthlyCard);
    console.log('monthlyCardInfo:', this.data.monthlyCardInfo);
    console.log('vehicleInfo:', this.data.vehicleInfo);
    
    if (this.data.hasMonthlyCard && this.data.monthlyCardInfo) {
      // 有月卡信息，跳转到月卡详情页面
      console.log('跳转到月卡详情页面，月卡信息:', this.data.monthlyCardInfo);
      
      const monthlyCardData = {
        vehicleId: this.data.vehicleId,
        cardInfo: this.data.monthlyCardInfo,
        vehicleInfo: this.data.vehicleInfo
      };
      
      console.log('准备传递的月卡数据:', monthlyCardData);
      const encodedData = encodeURIComponent(JSON.stringify(monthlyCardData));
      console.log('编码后的数据:', encodedData);
      
      const targetUrl = `/mine/pages/monthly-card-detail/monthly-card-detail?cardData=${encodedData}`;
      console.log('目标URL:', targetUrl);
      
      wx.navigateTo({
        url: targetUrl,
        success: () => {
          console.log('成功跳转到月卡详情页面');
        },
        fail: (err) => {
          console.error('跳转月卡详情页面失败:', err);
          console.error('错误详情:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      // 没有月卡信息，跳转到购买月卡页面
      console.log('跳转到购买月卡页面，车辆信息:', this.data.vehicleInfo);
      
      // 准备传递的车辆信息
      const vehicleData = {
        vehicleId: this.data.vehicleId,
        plateNumber: this.data.vehicleInfo.plateNumber || '',
        brand: this.data.vehicleInfo.brand || '',
        model: this.data.vehicleInfo.model || '',
        color: this.data.vehicleInfo.color || '',
        imageUrl: this.data.vehicleInfo.imageUrl || ''
      };
      
      console.log('准备传递的车辆数据:', vehicleData);
      
      // 将车辆信息编码后传递到月卡页面
      const encodedVehicleData = encodeURIComponent(JSON.stringify(vehicleData));
      
      wx.navigateTo({
        url: `/mine/pages/monthly-card/monthly-card?vehicleData=${encodedVehicleData}`,
        success: () => {
          console.log('成功跳转到月卡购买页面');
        },
        fail: (err) => {
          console.error('跳转月卡购买页面失败:', err);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 编辑车辆信息
  editVehicle() {
    wx.navigateTo({
      url: `/mine/pages/add-car/add-car?id=${this.data.vehicleId}&mode=edit`
    });
  },

  // 删除车辆
  deleteVehicle() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这辆车吗？删除后无法恢复。',
      confirmText: '删除',
      confirmColor: '#ff4444',
      success: (res) => {
        if (res.confirm) {
          this.confirmDeleteVehicle();
        }
      }
    });
  },

  // 确认删除车辆
  confirmDeleteVehicle() {
    console.log('确认删除车辆，ID:', this.data.vehicleId);
    
    // 这里可以调用删除接口
    http.delete('vehicle/vehicle/delete', { id: this.data.vehicleId })
    
    wx.showToast({
      title: '删除成功',
      icon: 'success'
    });
    
    setTimeout(() => {
      wx.navigateBack();
    }, 1500);
  },

  // 图片加载失败处理
  onImageError() {
    console.log('车辆图片加载失败，使用默认图片');
    this.setData({
      'vehicleInfo.imageUrl': '/mine/images/car.png'
    });
  },

  // 预览图片
  previewImage() {
    if (this.data.vehicleInfo.imageUrl) {
      wx.previewImage({
        urls: [this.data.vehicleInfo.imageUrl],
        current: this.data.vehicleInfo.imageUrl
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})